package com.metagurukul.metaspace.util;

import java.security.Security;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailSender {

	private static final String HOST = "smtp.gmail.com";
	private static final String USER = "test.bhagyesh@gmail.com";
	private static final String PASS = "nikku1008";

	public void sendConfirmationMail(Address to, String subject, Object text) {

		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", HOST);
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.quitwait", "false");

		Session session = Session.getInstance(props,
				new javax.mail.Authenticator() {

					@Override
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(USER, PASS);
					}
				});
		try {
			String messageBody = "Welcome to MetaSpace<br/>Your Login Details are...<br/>Username : "
					+ to + "<br/>Password : " + text.toString();
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(USER));
			message.addRecipient(Message.RecipientType.TO, to);
			message.setSubject(subject);
			message.setContent(messageBody, "text/html");

			Transport.send(message);

		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * method to send password to the authenticated user
	 * 
	 * @param email
	 *            valid email for which password is requested
	 * @throws AddressException 
	 */
	public void sendPassword(String email, String password) throws AddressException {
		if (password != null && email != null){
			try {
				sendConfirmationMail(new InternetAddress(email),
						"Your MetaSpace Password", password);
			} catch (AddressException e) {
				throw new AddressException();
			}
		}
	}
}